package com.topboya.linker.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.topboya.linker.R;
import com.topboya.linker.diyview.CenteredEditText;
import com.topboya.linker.diyview.group.GroupItemDecoration;
import com.topboya.linker.diyview.group.GroupRecyclerView;
import com.topboya.linker.model.levelitem.SelectProductGroup;
import com.topboya.linker.model.response.LatelyDataResponse;
import com.topboya.linker.model.response.ProductInforListReponse;
import com.topboya.linker.model.response.SelectFileResponse;
import com.topboya.linker.ui.adapter.ProductAdapter;
import com.topboya.linker.ui.adapter.SelectProductAdapter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.presenter.ProduceInfoPresenter;
import com.topboya.linker.ui.view.ProduceInfoView;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

public class SellectProductInforActivity extends BaseActivity<ProduceInfoView, ProduceInfoPresenter> implements ProduceInfoView {

    private static final String TAG = "SellectProductInforActivity:";
    private Toolbar toolbar;
    private GroupRecyclerView recycle_produceinfo;
    private CenteredEditText et_search_devices;
    private TextView toolbar_title;
    private TextView tv_toolbar_right;
    private Button btn_select;
    private Button btn_selected;
    private SmartRefreshLayout smart_refreshlayout;
    private RelativeLayout rl_selectall;
    private CheckBox ck_selectall;
    private  ArrayList<SelectFileResponse.FileList> selectFileList;
    private ArrayList<ProductInforListReponse.ProductDetailInfoList> productDetailInfoLists;
    private ArrayList<LatelyDataResponse.Data> lateDateList;
//    上次选中的状态，在下次还要被选中
    private ArrayList<SelectProductGroup> productoListslateselect;
    private List<SelectProductGroup> selectProductGroups;
    private  SelectProductAdapter selectProductAdapter;
    private int pageNo =1;
    private boolean isearch;
    private String position;
    private boolean loadmoreover =false;
    @Override
    protected int getLayoutId() {

        return R.layout.activity_select_productinfo;
    }

    @Override
    protected void initView() {
        isearch = false;
        toolbar = findViewById(R.id.toolbar);
        recycle_produceinfo = findViewById(R.id.recycle_produceinfo);
        toolbar_title = findViewById(R.id.toolbar_title);
        btn_select = findViewById(R.id.btn_select);
        btn_selected = findViewById(R.id.btn_selected);
        smart_refreshlayout = findViewById(R.id.smart_refreshlayout);
        tv_toolbar_right = findViewById(R.id.tv_toolbar_right);
        smart_refreshlayout.setEnableRefresh(false);//禁止刷新
        ck_selectall = findViewById(R.id.ck_selectall);
        et_search_devices = findViewById(R.id.et_search_devices);
        rl_selectall = findViewById(R.id.rl_selectall);
    }

    @Override
    protected void initData() {
        loadmoreover =false;
        toolbar_title.setText("选择产品");
        tv_toolbar_right.setVisibility(View.GONE);
        selectFileList =new ArrayList<>();
        selectProductGroups = new ArrayList<>();
        productDetailInfoLists = new ArrayList<>();
        lateDateList = new ArrayList<>();
        productoListslateselect=(ArrayList<SelectProductGroup>) getIntent().getSerializableExtra("productDetailInfoList");
//        LogUtils.v(TAG + "productoListslateselect:"+productoListslateselect.toString());
        if (null !=productoListslateselect){

            btn_selected.setText("已选择："+productoListslateselect.size());
        }

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
//      为代  item下面横线向目前是在条目布局加了一个view，后面改码设置
        recycle_produceinfo.addItemDecoration(new GroupItemDecoration<String, SelectProductGroup>());
        selectProductAdapter = new SelectProductAdapter(this,productDetailInfoLists,lateDateList);
        recycle_produceinfo.setLayoutManager(layoutManager);
        recycle_produceinfo.setAdapter(selectProductAdapter);
        recycle_produceinfo.notifyDataSetChanged();
        mPresenter.getLatelyData();


    }

    @Override
    protected void initListener() {

        et_search_devices.setOnClickListener(v -> {

             Intent intent = new Intent(SellectProductInforActivity.this,SearchProductInforActivity.class);
              intent.putExtra("productoListslateselect",productoListslateselect);
              startActivityForResult(intent,1001);

        });




        toolbar.setNavigationOnClickListener(v -> back());
         smart_refreshlayout.setOnLoadmoreListener(refreshlayout -> {

             if (loadmoreover){
                 UIUtils.showToast("没有更多的数据了");
                 return;
             }
             pageNo++;
             mPresenter.getProductInforList(String.valueOf(pageNo),null,"1");

         });
        selectProductAdapter.setOnItemClickListener((v, position, count) -> {

            btn_selected.setText("已选择："+count);

        });

        btn_selected.setOnClickListener(v -> {

            ArrayList<SelectProductGroup> productDetailInfoList= selectProductAdapter.getSelectedItem();
            if (null ==productDetailInfoList || productDetailInfoList.size() ==0){

                UIUtils.showToast("为选择产品，请先选择");
                return;
            }
            Intent intent = new Intent(SellectProductInforActivity.this,SeeSelectedProductActivity.class);
            intent.putExtra("productDetailInfoList",productDetailInfoList);
            startActivity(intent);


        });

        btn_select.setOnClickListener(v -> {

            //返回选择的产品集合
            ArrayList<SelectProductGroup> productDetailInfoList= selectProductAdapter.getSelectedItem();
            backTostartActivity(productDetailInfoList);

        });

        ck_selectall.setOnCheckedChangeListener((buttonView, isChecked) -> {

//            全选刷新所有的view
            if (isChecked){
                btn_selected.setText("已选择："+productDetailInfoLists.size());
            }else {
                btn_selected.setText("已选择：");
            }
            selectProductAdapter.selectAllorunSelectAll(isChecked);
        });

        rl_selectall.setOnClickListener(v -> {

          boolean  checked=  ck_selectall.isChecked();
          ck_selectall.setChecked(!checked);

            if (!checked){
                btn_selected.setText("已选择："+productDetailInfoLists.size());
            }else {

                btn_selected.setText("已选择：");
            }
            selectProductAdapter.selectAllorunSelectAll(!checked);


        });
    }

    @Override
    protected ProduceInfoPresenter createPresenter() {

        return new ProduceInfoPresenter(this);
    }


    @Override
    public void setProductInfoCustomeData(ArrayList<ProductInforListReponse.ProductDetailInfoList> productDetailInfoLists,String count) {
//        LogUtils.v(TAG+ "productDetailInfoLists0--:"+productDetailInfoLists.size());

            this.productDetailInfoLists.addAll(productDetailInfoLists);
//            if (this.productDetailInfoLists !=null &&Integer.valueOf(count) ==this.productDetailInfoLists.size()){
//                loadmoreover =true;
//                return;
//            }
            if (null !=productoListslateselect && productoListslateselect.size() >0){

                for (SelectProductGroup productDetailInfoList: productoListslateselect){

                    selectProductAdapter.setItemChecked(productDetailInfoList.getId(),productDetailInfoList);

                }
            }

        for (int i=0;i < lateDateList.size();i++){
//                LogUtils.v(TAG +"groupList.get(i).getOrgName():"+groupList.get(i).getOrgName());
            SelectProductGroup selectProductGroup = new SelectProductGroup();
            selectProductGroup.setProductName(lateDateList.get(i).getProductName());
            selectProductGroup.setId(lateDateList.get(i).getId());
            selectProductGroup.setProductFactory(lateDateList.get(i).getProductFactory());
            selectProductGroup.setFileNum(lateDateList.get(i).getFileNum());
            selectProductGroups.add(selectProductGroup);

        }
        for (int i = 0; i < productDetailInfoLists.size(); i++) {

            SelectProductGroup selectProductGroup = new SelectProductGroup();
            selectProductGroup.setProductName(productDetailInfoLists.get(i).getProductName());
            selectProductGroup.setId(productDetailInfoLists.get(i).getId());
            selectProductGroup.setProductFactory(productDetailInfoLists.get(i).getProductFactory());
            selectProductGroup.setFileNum(productDetailInfoLists.get(i).getFileNum());
            selectProductGroups.add(selectProductGroup);

        }
          selectProductAdapter.resetGroups();
          selectProductAdapter.setItemData(selectProductGroups);
//        将最近和所有的数据拼接起来，点击事件好取到对应的数据
         recycle_produceinfo.notifyDataSetChanged();
         smart_refreshlayout.finishLoadmore();


    }

    @Override
    public void setLatelyData(List<LatelyDataResponse.Data> latelyData) {

        lateDateList.clear();
        lateDateList.addAll(latelyData);
        mPresenter.getProductInforList(String.valueOf(pageNo),null,"1");


    }

    private void backTostartActivity(ArrayList<SelectProductGroup> productDetailInfoList) {

        //数据是使用Intent返回
        Intent intent = new Intent();
        //把返回数据存入Intent
        intent.putExtra("productDetailInfoList", productDetailInfoList);
        intent.putExtra("isDoc", false);
//        intent.putExtra("fileLists", fileListss);
        //设置返回数据
        setResult(1002, intent);
        //关闭Activity
        finish();
    }

    //   返回选择的资料，遍历拿资料的时候直接去选中的产品集合中遍历，不用从总得集合中遍历，这样就节约很多时间
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
         LogUtils.v(TAG + "intent:"+intent);
        if (null !=intent){

            LogUtils.v(TAG +"requestCode:"+requestCode+"--resultCode"+resultCode);

            ArrayList<SelectFileResponse.FileList> fileLists= (ArrayList<SelectFileResponse.FileList>) intent.getSerializableExtra("fileLists");
//            拿到资料信息中
            position = intent.getStringExtra("position");
            LogUtils.v(TAG+"position"+position);
            selectProductGroups.get(Integer.valueOf(position)).setFileLists(fileLists);
            selectProductAdapter.notifyDataSetChanged();
            LogUtils.v(TAG+"position"+position+"fileLists:"+fileLists.size());
        }
    }

    @Override
    public void onBackPressed() {

        back();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        } else { // 如果不是back键正常响应
            return super.onKeyDown(keyCode, event);
        }
    }

    private void back() {

        ArrayList<SelectProductGroup> productDetailInfoList= selectProductAdapter.getSelectedItem();
        backTostartActivity(productDetailInfoList);

    }


}